import { useState } from "react";
import "./index.css";

interface CalendarProps {
    defaultValue?:Date;
    onChange:(date:Date)=> void
}

export default function CustomCalendar(props:CalendarProps) {
    let { defaultValue = new Date() , onChange } = props

	const [date, setDate] = useState(defaultValue);

	const handlePrevMonth = () => {
		setDate(new Date(date.getFullYear(), date.getMonth() - 1, 1));
	};

	const handleNextMonth = () => {
		setDate(new Date(date.getFullYear(), date.getMonth() + 1, 1));
	};

    //  计算当月天数
	const daysOfMonth = (year: number, month: number) =>
		new Date(year, month + 1, 0).getDate(); // 这样实际上返回的是当前月的最后一天

    // 计算当月第一天是星期几
	const firstDayOfMonth = (year: number, month: number) =>
		new Date(year, month, 1).getDay(); //  返回该月的第一天是星期几

    /* 
    渲染日期的核心是：
    计算当月的天数和当月第一天是周几 前面的天数用空白填充即可
    */
	const renderDates = () => {
		const days = [];
        // daysCount：通过 daysOfMonth 函数获取当前月份的天数。
		const daysCount = daysOfMonth(date.getFullYear(), date.getMonth());
        // firstDay：通过 firstDayOfMonth 获取当前月份第一天是星期几。
		const firstDay = firstDayOfMonth(date.getFullYear(), date.getMonth());

		for (let i = 0; i < firstDay; i++) {
			days.push(<div key={`empty-${i}`} className="empty"></div>);
		}
        

		for (let i = 1; i <= daysCount; i++) {
            if(i === date.getDate()){
                days.push(<div key={i} className="day selected">{i}</div>);
            }else{
                days.push(<div key={i} onClick={()=> clickHandle(i)} className="day">{i}</div>);
            }
			
		}

		return days;
	};

    const clickHandle = (i:number) => {
        const curDate = new Date(date.getFullYear(), date.getMonth(), i);
        setDate(curDate);
        onChange?.(curDate);
    }




	return (
		<div className="flexContainer jCCenter">
			<div className="calendar">
				<div className="header">
					<button onClick={handlePrevMonth}>&lt;</button>
					<div>
						{date.getFullYear()} 年 {date.getMonth() + 1} 月
					</div>
					<button onClick={handleNextMonth}>&gt;</button>
				</div>
				<div className="days">
					<div className="day">日</div>
					<div className="day">一</div>
					<div className="day">二</div>
					<div className="day">三</div>
					<div className="day">四</div>
					<div className="day">五</div>
					<div className="day">六</div>
					{renderDates()}
				</div>
			</div>
		</div>
	);
}
